package com.example.module_mine.login

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.lib_common.appContext
import com.example.lib_common.base.BaseActivity
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.base.utils.ToastUtils
import com.example.lib_common.base.utils.ValidUtil
import com.example.lib_common.clickFlow
import com.example.lib_common.getAttrValue
import com.example.lib_common.throttleFirst
import com.example.module_mine.R
import com.example.module_mine.databinding.FragmentPhoneLoginBinding
import com.example.module_mine.helper.PopupAgreementHelper
import com.example.module_mine.viewmodel.MineViewModel
import com.example.module_mine.widget.IntentData
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

@AndroidEntryPoint
class PhoneLoginFragment : BaseFragment<MineViewModel,FragmentPhoneLoginBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_phone_login
    private val mViewModel:MineViewModel by activityViewModels()
    private lateinit var mNavController: NavController
    private var mLoginAgreement: Boolean = false
    override fun initView() {
        super.initView()
        mViewModel.setShowingFragmentTag(PhoneLoginFragment::class.simpleName!!)
        mNavController = Navigation.findNavController(mBinding.root)
        initAgreementCheckBox(mLoginAgreement)
        initAgreementView()
    }
    private val mPopupAgreement by lazy {
        PopupAgreementHelper(layoutInflater)
    }
    override fun initData() {
        mBinding.viewModel = mViewModel
    }
    override fun initListener() {

        mBinding.ivWechat.setOnClickListener {
            if (!mLoginAgreement) {
                (activity as BaseActivity<*, *>?)?.dismissKeyboard()
                mPopupAgreement.show(mBinding.btnCheck)
                return@setOnClickListener
            }
            //获取微信Code
//            WxHelper.get(appContext).auth(requireContext().packageName)
        }
        mBinding.apply {
            viewModel = mViewModel
            //隐私政策
            vChecked.setOnClickListener {
                mLoginAgreement = !mLoginAgreement
                initAgreementCheckBox(mLoginAgreement)
            }
            //验证码
            btnSmsCode.clickFlow()
                .throttleFirst(800)
                .onEach {
                    checkPhone()
                }
                .launchIn(lifecycleScope)

            etPhone.setOnEditorActionListener { _, i, _ ->
                if (i == EditorInfo.IME_ACTION_DONE) {
                    checkPhone()
                }
                true
            }
        }

//        mViewModel.requestLoginEvent.observeWithLifecycle(this, Lifecycle.State.CREATED) {
//            when (it) {
//                is Success -> {
//                    setLoadingViewVisible(false)
//                    //验证码登录成功
//                    (activity as? LoginActivity)?.handleLoginSuccess()
//                }
//
//                is Loading -> {
//                    JVerificationInterface.dismissLoginAuthActivity()
//                    setLoadingViewVisible(true)
//                }
//
//                is Failed -> {
//                    ToastUtils.showShort(requireContext(), it.message)
//                    setLoadingViewVisible(false)
//                    if (it.message == "未绑定手机号") {
//                        mNavController.navigate(R.id.action_phoneLoginFragment_to_bindPhoneFragment)
//                    }
//                }
//
//                else -> {
//
//                }
//            }
//        }


        //微信code事件
//        mWxEventObserver = observeEvent<WeChatCodeEvent>(minActiveState = Lifecycle.State.STARTED) {
//            ApplicationScopeViewModelProvider.getApplicationScopeViewModel(EventBusCore::class.java)
//            if (it.code.isNotEmpty()) {
//                if (mViewModel.wxCode != it.code) {
//                    mViewModel.wxCode = it.code
//                    mViewModel.loginByWX(it.code)
//                } else {
//                    mViewModel.wxCode = ""
//                }
//            } else {
//                ToastUtils.showShort(context, "微信code为空")
//            }
//        }

        /**授权登录*/
        mBinding.ivCyclone.setOnClickListener {
            if (!mLoginAgreement) {
                (activity as BaseActivity<*, *>?)?.dismissKeyboard()
                mPopupAgreement.show(mBinding.btnCheck)
                return@setOnClickListener
            }
//            val isInstalled = CycloneAuthHelper.getInstance().isInstalled(appContext)
//            if (!isInstalled) {
//                ToastUtils.showShort(requireActivity(), "授权失败，赛科龙未安装!")
//                return@setOnClickListener
//            }
//            CycloneAuthHelper.getInstance().setAuthCallback(object : CycloneAuthHelper.AuthCallback {
//                override fun onResult(code: Int, token: String?) {
//                    Log.d("xxx", "PhoneLoginFragment auth -> onResult -> $code -- ${token}")
//                    if (code == 0 && !token.isNullOrEmpty()) {
//                        mViewModel.authLogin(token)
//                    }else{
//                        ToastUtils.showShort(appContext,"授权失败[${code}]")
//                    }
//                }
//            })
//            CycloneAuthHelper.getInstance().auth(requireActivity())
        }


    }
    private fun checkPhone() {
        val phone = mViewModel.phone.value

        if (!mLoginAgreement) {
            (activity as BaseActivity<*, *>?)?.dismissKeyboard()
            //ToastUtils.showShort(context, "请先勾选同意《用户协议》和《隐私政策》")
            mPopupAgreement.show(mBinding.btnCheck)
            return
        }

        if (!ValidUtil.phoneNumberValid(phone)) {
            ToastUtils.showShort(context, "手机号码长度错误")
            return
        }

//        if (!ValidUtil.isMobile(phone)) {
//            ToastUtils.showShort(context, "手机号码格式错误")
//            return
//        }

        //跳转输入验证码页面
        mViewModel.requestRest = false
        mNavController.navigate(R.id.action_phoneLoginFragment_to_smsCodeFragment, bundleOf(
            IntentData.KEY_ACTION_SMS_CODE to SmsCode.LOGIN.type)
        )
    }
    //隐私政策Check背景切换
    private fun initAgreementCheckBox(checked: Boolean) {
        if (!checked) {
            mBinding.btnCheck.background = ContextCompat.getDrawable(appContext, R.mipmap.icon_uncheck)
        } else {
            mPopupAgreement.dismiss()
            mBinding.btnCheck.background = ContextCompat.getDrawable(appContext, R.mipmap.icon_checked)
        }
    }
    //用户协议 隐私政策
    private fun initAgreementView() {
        val colorMain = getAttrValue(requireContext()!!, R.attr.colorTheme)
        val userAgreement = "《用户协议》"
        val privacyPolicy = "《隐私政策》"
        val content = "阅读并同意$userAgreement 和$privacyPolicy"
        val spannableStringBuilder = SpannableStringBuilder(content)
        val userAgreementStart = content.indexOf(userAgreement)
        val userAgreementEnd = userAgreementStart + userAgreement.length

        val privacyPolicyStart = content.indexOf(privacyPolicy)
        val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length

        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
//                CommonWebActivity.jumpUserAgreement()
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(requireContext(), colorMain)
                ds.isUnderlineText = false
            }

        }, userAgreementStart, userAgreementEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        spannableStringBuilder.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
//                CommonWebActivity.jumpPrivacyAgreement()
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(requireContext(), colorMain)
                ds.isUnderlineText = false
            }

        }, privacyPolicyStart, privacyPolicyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        mBinding.tvAgreement.highlightColor = Color.TRANSPARENT
        mBinding.tvAgreement.text = spannableStringBuilder
        mBinding.tvAgreement.movementMethod = LinkMovementMethod.getInstance()
    }
    override fun onDestroy() {
        super.onDestroy()
    }

}